import seedAgent from '@/services/seedAgent-service';
import {
  ArrowLeftOutlined,
  DeleteOutlined,
  EditOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import {
  Button,
  Card,
  Descriptions,
  Modal,
  Space,
  Table,
  Tabs,
  Tag,
  message,
} from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import SeedAgentForm from '../SeedAgentForm';
import DataRuleForm from './DataRuleForm';

const { TabPane } = Tabs;

const SeedAgentDetail: React.FC = () => {
  const { agent_id } = useParams();
  const navigate = useNavigate();
  const [agentDetail, setAgentDetail] = useState<any>(null);
  const [dataRules, setDataRules] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [isRuleModalVisible, setIsRuleModalVisible] = useState(false);
  const [currentRule, setCurrentRule] = useState<any>(null);

  const fetchAgentDetail = async () => {
    setLoading(true);
    try {
      const res = await seedAgent.seed_agent_detail({ agent_id });
      const response = res.data;
      setAgentDetail(response.data);
    } catch (error) {
      message.error('获取代理详情失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const fetchDataRules = async () => {
    setLoading(true);
    try {
      const res = await seedAgent.data_rules_list({ agent_id });
      const response = res.data;
      setDataRules(response.data.list);
    } catch (error) {
      message.error('获取数据规则失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (agent_id) {
      fetchAgentDetail();
      fetchDataRules();
    }
  }, [agent_id]);

  const handleDeleteAgent = () => {
    Modal.confirm({
      title: '确认删除此代理？',
      content: '所有关联的数据规则也将被删除。',
      onOk: async () => {
        try {
          await seedAgent.seed_agent_delete({ agent_id });
          message.success('代理删除成功');
          navigate('/dataManager/seedAgentManager');
        } catch (error) {
          message.error('删除代理失败');
          console.error(error);
        }
      },
    });
  };

  const handleDeleteRule = (ruleId: string) => {
    Modal.confirm({
      title: '确认删除此数据规则？',
      onOk: async () => {
        try {
          await seedAgent.data_rules_delete({ rule_id: ruleId });
          message.success('数据规则删除成功');
          fetchDataRules();
        } catch (error) {
          message.error('删除数据规则失败');
          console.error(error);
        }
      },
    });
  };

  const columns = [
    {
      title: '可用数据',
      dataIndex: 'available_data',
      key: 'available_data',
    },

    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      render: (timestamp: number) =>
        dayjs.unix(timestamp).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'actions',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button
            icon={<EditOutlined />}
            onClick={() => {
              setCurrentRule(record);
              setIsRuleModalVisible(true);
            }}
          />
          <Button
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteRule(record.rule_id)}
            danger
          />
        </Space>
      ),
    },
  ];

  if (!agentDetail) return <div>加载中...</div>;
  if (!agent_id) {
    return <div>缺少代理ID</div>;
  }
  return (
    <div>
      <Button
        type="text"
        icon={<ArrowLeftOutlined />}
        onClick={() => navigate('/dataManager/seedAgentManager')}
        style={{ marginBottom: 16 }}
      >
        返回列表
      </Button>

      <Card
        title={agentDetail.purpose}
        extra={
          <Space>
            <Button
              icon={<EditOutlined />}
              onClick={() => setIsEditModalVisible(true)}
            >
              编辑
            </Button>
            <Button
              icon={<DeleteOutlined />}
              onClick={handleDeleteAgent}
              danger
            >
              删除
            </Button>
          </Space>
        }
      >
        <Tabs defaultActiveKey="1">
          <TabPane tab="基本信息" key="1">
            <Descriptions bordered column={2}>
              <Descriptions.Item label="目的">
                {agentDetail.purpose}
              </Descriptions.Item>
              <Descriptions.Item label="数据源">
                {agentDetail.data_source}
              </Descriptions.Item>
              <Descriptions.Item label="知识库">
                {agentDetail.knowledge_base}
              </Descriptions.Item>
              <Descriptions.Item label="重要性">
                <Tag
                  color={
                    agentDetail.importance > 7
                      ? 'red'
                      : agentDetail.importance > 5
                        ? 'orange'
                        : 'green'
                  }
                >
                  {agentDetail.importance}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">
                {dayjs.unix(agentDetail.create_time).format('YYYY-MM-DD HH:mm')}
              </Descriptions.Item>
              <Descriptions.Item label="更新时间">
                {dayjs.unix(agentDetail.update_time).format('YYYY-MM-DD HH:mm')}
              </Descriptions.Item>
              <Descriptions.Item label="描述" span={2}>
                {agentDetail.description || '无'}
              </Descriptions.Item>
            </Descriptions>
          </TabPane>
          <TabPane tab="数据规则" key="2">
            <div style={{ marginBottom: 16 }}>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => {
                  setCurrentRule(null);
                  setIsRuleModalVisible(true);
                }}
              >
                添加数据规则
              </Button>
            </div>
            <Table
              columns={columns}
              dataSource={dataRules}
              rowKey="rule_id"
              loading={loading}
            />
          </TabPane>
        </Tabs>
      </Card>

      <Modal
        title="编辑种子代理"
        visible={isEditModalVisible}
        onCancel={() => setIsEditModalVisible(false)}
        footer={null}
        destroyOnClose
      >
        <SeedAgentForm
          initialValues={agentDetail}
          mode="edit"
          onSuccess={() => {
            setIsEditModalVisible(false);
            fetchAgentDetail();
          }}
        />
      </Modal>

      <Modal
        title={currentRule ? '编辑数据规则' : '添加数据规则'}
        visible={isRuleModalVisible}
        onCancel={() => setIsRuleModalVisible(false)}
        footer={null}
        destroyOnClose
      >
        <DataRuleForm
          agent_id={agent_id}
          initialValues={currentRule}
          onSuccess={() => {
            setIsRuleModalVisible(false);
            fetchDataRules();
          }}
        />
      </Modal>
    </div>
  );
};

export default SeedAgentDetail;
